import { ErrorTypes, handleError } from './errorHandler';

// 默认城市配置
export const DEFAULT_LOCATION = {
    latitude: 31.230416,
    longitude: 121.473701,
    city: '上海市',
    district: '黄浦区',
    province: '上海市',
};

// 检查定位权限
export const checkLocationAuth = () => {
    return new Promise((resolve) => {
        uni.getSetting({
            success: (res) => {
                resolve(res.authSetting['scope.userLocation'] === true);
            },
            fail: () => {
                resolve(false);
            },
        });
    });
};

// 获取位置的主函数
export const getCurrentLocation = async () => {
    try {
        const authStatus = await checkLocationAuth();

        // 如果没有权限，使用默认位置
        if (!authStatus) {
            return getLastKnownLocation();
        }

        const locationInfo = await getDetailedLocation();
        if (locationInfo.latitude) {
            return locationInfo;
        } else {
            return DEFAULT_LOCATION;
        }
    } catch (error) {
        
        return getLastKnownLocation();
    }
};

// 获取具体位置信息
export const getDetailedLocation = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
            success: (res) => {
                resolve({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    city: '',
                    district: '',
                    province: '',
                });
            },
            fail: (error) => {
                
                reject(error);
            },
        });
    });
};

// 保存位置信息到本地
export const saveLocationToStorage = (location) => {
    try {
        uni.setStorageSync('last_known_location', location);
    } catch (error) {
        console.error('保存位置信息失败:', error);
    }
};

// 从本地获取上次的位置信息
export const getLastKnownLocation = () => {
    try {
        return uni.getStorageSync('last_known_location') || DEFAULT_LOCATION;
    } catch (error) {
        console.error('获取本地位置信息失败:', error);
        return DEFAULT_LOCATION;
    }
};

// 选择位置
export const chooseLocation = () => {
    return new Promise((resolve) => {
        uni.chooseLocation({
            success: (res) => {
                // 将选择的位置信息转换为标准格式
                const locationInfo = {
                    latitude: res.latitude,
                    longitude: res.longitude,
                    city: res.name || '未知城市',
                    district: '',
                    province: '',
                };
                resolve(locationInfo);
            },
            fail: (err) => {
                
                // 用户取消选择或未授权时，静默返回当前位置
                resolve(getLastKnownLocation());
            },
        });
    });
};
